package com.example.codereview;

import com.intellij.util.ui.ImageUtil;

import javax.imageio.ImageIO;
import javax.swing.*;
import javax.swing.text.BadLocationException;
import javax.swing.text.SimpleAttributeSet;
import javax.swing.text.StyleConstants;
import javax.swing.text.StyledDocument;
import javax.swing.text.rtf.RTFEditorKit;
import java.awt.*;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.Transferable;
import java.awt.datatransfer.UnsupportedFlavorException;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.image.BufferedImage;
import java.io.*;

/**
 * @author xianfeng
 * @date 2024/11/11 11:55
 * @description:
 */
public class CustomJTextPaneback1 extends JTextPane {

    public CustomJTextPaneback1() {
        super();
    }

    // 将 JTextPane 的内容序列化为 byte[]
    public byte[] getSerializeText() {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        RTFEditorKit rtfKit = new RTFEditorKit();
        try {
            rtfKit.write(baos, this.getStyledDocument(), 0, this.getDocument().getLength());
        } catch (IOException e) {
            throw new RuntimeException(e);
        } catch (BadLocationException e) {
            throw new RuntimeException(e);
        }
        return baos.toByteArray();
    }

    // 将序列化的内容反序列化到 JTextPane
    public void setSerializeText(byte[] serializedContent) {
        if (serializedContent != null) {
            ByteArrayInputStream bais = new ByteArrayInputStream(serializedContent);
            RTFEditorKit rtfKit = new RTFEditorKit();
            try {
                rtfKit.read(bais, this.getStyledDocument(), 0);
            } catch (IOException e) {
                throw new RuntimeException(e);
            } catch (BadLocationException e) {
                throw new RuntimeException(e);
            }
        }
    }

    public void addPasteImageListener() {
        JTextPane textPane = this;
        //textPane.setTransferHandler(new ImageTransferHandler());

       /* textPane.getInputMap(JComponent.WHEN_FOCUSED).put(KeyStroke.getKeyStroke("ctrl V"), "pasteImage");
        textPane.getActionMap().put("pasteImage", new AbstractAction() {
            @Override
            public void actionPerformed(ActionEvent e) {
                pasteImage(textPane);
            }
        });*/

        /*this.addKeyListener(new KeyAdapter() {
            @Override
            public void keyPressed(KeyEvent e) {
                System.out.println(e.getModifiersEx() & KeyEvent.CTRL_DOWN_MASK);
                System.out.println(e.getKeyCode());
                System.out.println(KeyEvent.VK_V);
                if ((e.getModifiersEx() & KeyEvent.CTRL_DOWN_MASK) != 0 && e.getKeyCode() == KeyEvent.VK_V) {
                    pasteImage(jTextPane);
                }
            }
        });*/
    }

    public void pasteImage() {
        JTextPane textPane = this;
        Transferable t = Toolkit.getDefaultToolkit().getSystemClipboard().getContents(null);
        if (t != null && t.isDataFlavorSupported(DataFlavor.imageFlavor)) {
            try {
                Image image = (Image) t.getTransferData(DataFlavor.imageFlavor);
                BufferedImage bufferedImage = ImageUtil.createImage(image.getWidth(null), image.getHeight(null), BufferedImage.TYPE_INT_ARGB);
                Graphics2D g2d = bufferedImage.createGraphics();
                g2d.drawImage(image, 0, 0, null);
                g2d.dispose();
                // 创建可调整大小的图片组件并插入到 textPane
                SmoothResizableImageLabel imageLabel = new SmoothResizableImageLabel(bufferedImage);
                textPane.insertComponent(imageLabel);
            } catch (UnsupportedFlavorException | IOException ex) {
                ex.printStackTrace();
            }
        }
    }


    private class ImageTransferHandler extends TransferHandler {
        @Override
        public boolean canImport(TransferSupport support) {
            // 仅接受图片格式的数据
            return support.isDataFlavorSupported(DataFlavor.imageFlavor) || support.isDataFlavorSupported(DataFlavor.stringFlavor);
        }

        @Override
        public boolean importData(TransferSupport support) {
            if (!canImport(support)) {
                return false;
            }
            try {
                Transferable transferable = support.getTransferable();

                // 检查是否为图片
                if (transferable.isDataFlavorSupported(DataFlavor.imageFlavor)) {
                    Image image = (Image) transferable.getTransferData(DataFlavor.imageFlavor);
                    insertImageIntoTextPane(image);
                }
                // 检查是否为文本
                else if (transferable.isDataFlavorSupported(DataFlavor.stringFlavor)) {
                    String text = (String) transferable.getTransferData(DataFlavor.stringFlavor);
                    CustomJTextPaneback1.this.getDocument().insertString(CustomJTextPaneback1.this.getCaretPosition(), text, null);
                }
                return true;
            } catch (Exception e) {
                e.printStackTrace();
                return false;
            }
        }

        private void insertImageIntoTextPane(Image image) {
            StyledDocument doc = CustomJTextPaneback1.this.getStyledDocument();
            SimpleAttributeSet attrSet = new SimpleAttributeSet();
            StyleConstants.setIcon(attrSet, new ImageIcon(image));
            try {
                // 插入图片到文本框中
                doc.insertString(doc.getLength(), "ignored text", attrSet);
            } catch (BadLocationException e) {
                e.printStackTrace();
            }
        }
    }

    static class SmoothResizableImageLabel extends JLabel implements Serializable {
        private int mouseX, mouseY;
        private final int CORNER_SIZE = 10; // 拖拽角的大小
        private final Cursor SE_RESIZE_CURSOR = new Cursor(Cursor.SE_RESIZE_CURSOR);
        private final Cursor DEFAULT_CURSOR = new Cursor(Cursor.DEFAULT_CURSOR);

        private boolean isResizing = false;
        private transient BufferedImage originalImage;
        private Dimension targetSize; // 用于记录目标尺寸

        private byte[] imageData; // 存储序列化的字节流数据

        public SmoothResizableImageLabel(BufferedImage image) {
            super(new ImageIcon(image));
            this.imageData = serializeImage(image); // 将图像序列化为字节流
            this.originalImage = image;
            this.targetSize = new Dimension(image.getWidth(), image.getHeight());
            setSize(targetSize);
            setBorder(BorderFactory.createLineBorder(Color.GRAY, 1));

            addMouseListener(new MouseAdapter() {
                @Override
                public void mousePressed(MouseEvent e) {
                    if (isInCorner(e.getX(), e.getY())) {
                        isResizing = true;
                        mouseX = e.getX();
                        mouseY = e.getY();
                        setCursor(SE_RESIZE_CURSOR);
                    }
                }

                @Override
                public void mouseReleased(MouseEvent e) {
                    isResizing = false;
                    setCursor(DEFAULT_CURSOR);
                    resizeImageToTargetSize(); // 在拖动结束时更新图片大小
                }
            });

            addMouseMotionListener(new MouseAdapter() {
                @Override
                public void mouseMoved(MouseEvent e) {
                    if (isInCorner(e.getX(), e.getY())) {
                        setCursor(SE_RESIZE_CURSOR);
                    } else {
                        setCursor(DEFAULT_CURSOR);
                    }
                }

                @Override
                public void mouseDragged(MouseEvent e) {
                    if (isResizing) {
                        int deltaX = e.getX() - mouseX;
                        int deltaY = e.getY() - mouseY;

                        int newWidth = Math.max(20, getWidth() + deltaX);
                        int newHeight = Math.max(20, getHeight() + deltaY);

                        targetSize.setSize(newWidth, newHeight);
                        setSize(targetSize);
                        revalidate();
                        repaint();
                    }
                }
            });
        }

        // 判断鼠标是否在图片的右下角区域
        private boolean isInCorner(int x, int y) {
            return x >= getWidth() - CORNER_SIZE && y >= getHeight() - CORNER_SIZE;
        }

        // 用高质量的模式缩放图片
        private void resizeImageToTargetSize() {
            BufferedImage resizedImage = new BufferedImage(
                    targetSize.width, targetSize.height, BufferedImage.TYPE_INT_ARGB);
            Graphics2D g2d = resizedImage.createGraphics();
            g2d.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
            g2d.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
            g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
            g2d.drawImage(originalImage, 0, 0, targetSize.width, targetSize.height, null);
            g2d.dispose();

            setIcon(new ImageIcon(resizedImage));
        }


        // 将图像转换为字节流
        private byte[] serializeImage(BufferedImage image) {
            try {
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                ImageIO.write(image, "png", baos); // 使用 PNG 格式
                baos.flush();
                return baos.toByteArray();
            } catch (IOException e) {
                e.printStackTrace();
                return null;
            }
        }

        // 反序列化图像
        private void deserializeImage() {
            if (imageData != null) {
                try {
                    ByteArrayInputStream bais = new ByteArrayInputStream(imageData);
                    originalImage = ImageIO.read(bais);
                    setIcon(new ImageIcon(originalImage)); // 显示反序列化后的图像
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

        // 重写 readObject 来处理反序列化
        private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException {
            in.defaultReadObject(); // 默认反序列化
            deserializeImage(); // 反序列化图像
        }
    }

}
